package com.swt.gap.util;

import com.swt.gap.common.constant.CommonConstant;
import org.springframework.util.StringUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 请填写说明
 *
 * @author sx
 * @date 2020/8/27 16:52
 */
public class EmailUtil {


    public static Email parseEmlFile(String filePath) {
        Email email = new Email();
        InputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            Session mailSession = Session.getDefaultInstance(new Properties(), null);
            MimeMessage msg = new MimeMessage(mailSession,fis);
            Address[] from = msg.getFrom();
            email.setFrom((InternetAddress) from[0]);
//            email.setTime(msg.ge);
            List<InternetAddress> recipients = new ArrayList<>();
            Address[] allRecipients = msg.getAllRecipients();
            for (Address recipient : allRecipients) {
                InternetAddress address = (InternetAddress) recipient;
                recipients.add(address);
            }
            email.setRecipients(recipients);
            email.setSubject(msg.getSubject());
            Email partContent = new Email();
            Object content = msg.getContent();
            if (content instanceof Multipart) {
                Multipart multipart = (Multipart) content;
                partContent = EmailUtil.parseMultipart(multipart);

            } else if (content instanceof Part) {
                Part part = (Part) content;
                partContent = EmailUtil.parsePart(part);
            } else {
                partContent = Email.builder().content(msg.getContent().toString()).build();
            }
            if (null != partContent.getContent()) {
                email.setContent(partContent.getContent());
            }
            if (null != partContent.getAttachments()) {
                List<String> attachments = new ArrayList<>();
                attachments.addAll(partContent.getAttachments());
                email.setAttachments(attachments);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return email;
    }


    public static Email parseMultipart(Multipart multipart) throws Exception {
        Email retValue = new Email();
        for (int i = 0; i < multipart.getCount(); i++) {
            Email partContent;
            Part part = multipart.getBodyPart(i);
            // 每部分可能是邮件内容,
            // 也可能是另一个小包裹(MultipPart)
            // 判断此包裹内容是不是一个小包裹, 一般这一部分是 正文 Content-Type: multipart/alternative
            if (part.getContent() instanceof Multipart) {
                Multipart p = (Multipart) part.getContent();// 转成小包裹
                // 递归迭代
                partContent = parseMultipart(p);

            } else {
                partContent = parsePart(part);
            }

            if (null != partContent.getContent()) {
                String preContent = retValue.getContent() == null ? "" : retValue.getContent();
                retValue.setContent(preContent + partContent.getContent());
            } else if (null != partContent.getAttachments()) {
                List<String> attachments = null == retValue.getAttachments()?new ArrayList<>() : retValue.getAttachments();
                attachments.addAll(partContent.getAttachments());
                retValue.setAttachments(attachments);
            }
        }
        return retValue;
    }

    /**
    * @param part
    * 解析内容
    * @throws Exception
    */
    public static Email parsePart(Part part) throws Exception {
        Email email = new Email();
        if (part.getDisposition() != null) {
            String strFileName = part.getFileName();
            if(!StringUtils.isEmpty(strFileName)) {
                // MimeUtility.decodeText解决附件名乱码问题
                strFileName = MimeUtility.decodeText(strFileName);
                System.out.println("发现附件: "+ strFileName);

                InputStream in = part.getInputStream();
                // 读取附件字节并存储到文件中
                String filePath = CommonConstant.UPLOAD_DIR + strFileName;
                FileOutputStream out = new FileOutputStream(filePath);
                int data;
                while ((data = in.read()) != -1) {
                    out.write(data);
                }
                in.close();
                out.close();
                List<String> attachments = new ArrayList<>();
                attachments.add(strFileName);
                email.setAttachments(attachments);
            }

        } else {
            email.setContent(part.getContent().toString());
        }

        return email;
    }

}
